package com.kinglone.front;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.kinglone.back.blog.model.Blog;
import com.kinglone.back.blog.service.BlogService;
import com.kinglone.back.comment.model.Comment;
import com.kinglone.back.comment.service.CommentService;
import com.kinglone.common.lucene.BlogIndex;
import com.kinglone.common.utils.ResponseUtil;
import com.kinglone.common.utils.StringUtil;

@Controller
@RequestMapping("/front")
public class BlogFrontController {

	@Autowired
	private BlogService blogService;
	@Autowired
	private CommentService commentService;
	
	// 博客索引
	private BlogIndex blogIndex=new BlogIndex();
	
	/**
	 * 查看文章详情
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/articles/{id}")
	public ModelAndView details(@PathVariable("id") Integer id,HttpServletRequest request){
		ModelAndView mv = new ModelAndView("mainTemp");
		Blog blog = blogService.findBlogById(id);
		String keyWords = blog.getKeyWord();
		if(StringUtil.isNotEmpty(keyWords)){
			String arr[] = keyWords.split(" ");
			mv.addObject("keyWords", StringUtil.filterWhite(Arrays.asList(arr)));		
		}else{
			mv.addObject("keyWords", null);
		}
		mv.addObject("blog", blog);
		blog.setClickHit(blog.getClickHit()+1);//博客点击次数加1
		blogService.update(blog);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("blogId", blog.getId());
		map.put("state", 1); // 查询审核通过的评论
		mv.addObject("commentList", commentService.list(map)); 
		mv.addObject("mainPage", "/front/view.jsp");
		mv.addObject("pageCode", this.genUpAndDownPageCode(blogService.getLastBlog(id),blogService.getNextBlog(id),request.getServletContext().getContextPath()));
		mv.addObject("pageTitle",blog.getTitle()+"_kinglone的个人博客系统");
		mv.addObject("description",blog.getSummary()+"_kinglone的个人博客系统");
		return mv;
	}
	/**
	 * 获取下一篇博客和下一篇博客代码
	 * @param lastBlog
	 * @param nextBlog
	 * @return
	 */
	private String genUpAndDownPageCode(Blog lastBlog,Blog nextBlog,String projectContext){
		StringBuffer pageCode=new StringBuffer();
		if(lastBlog==null || lastBlog.getId()==null){
			pageCode.append("<p>上一篇：没有了</p>");
		}else{
			pageCode.append("<p>上一篇：<a href='"+projectContext+"/front/articles/"+lastBlog.getId()+".html'>"+lastBlog.getTitle()+"</a></p>");
		}
		if(nextBlog==null || nextBlog.getId()==null){
			pageCode.append("<p>下一篇：没有了</p>");
		}else{
			pageCode.append("<p>下一篇：<a href='"+projectContext+"/front/articles/"+nextBlog.getId()+".html'>"+nextBlog.getTitle()+"</a></p>");
		}
		return pageCode.toString();
	}
	/**
	 * 发表评论
	 * @param comment
	 * @param imageCode
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveComment")
	public String saveComment(Comment commentTemp,@RequestParam(value="imageCode")String imageCode,HttpServletRequest request,HttpServletResponse response)throws Exception{
		String sRand=(String) request.getSession().getAttribute("sRand"); // 获取系统生成的验证码
		JSONObject result = new JSONObject();
		int resultTotal = 0;
		if(!sRand.equals(imageCode)){
			result.put("success", false);
			result.put("errorMessage", "验证码填写错误!");
		}else{
			request.getSession().setAttribute("sRand", "");//清除验证码
			Comment comment = new Comment();
			String email = request.getParameter("email");
			String content = request.getParameter("content");			
			String userIp = request.getRemoteAddr();
			comment.setUserIp(userIp);
			comment.setBlog(commentTemp.getBlog());
			comment.setContent(content);
			comment.setEmail(email);
			resultTotal=commentService.add(comment);
			// 该博客的评论次数加1
			Blog blog=blogService.findBlogById(commentTemp.getBlog().getId());
			blog.setReplyHit(blog.getReplyHit()+1);
			blogService.update(blog);	
			if(resultTotal > 0){
				result.put("success", true);
			}else{
				result.put("success", false);
				result.put("errorMessage", "评论失败!");
			}
		}
		ResponseUtil.write(response, result);
		return null;
	}
	
	@RequestMapping("/q")
	public ModelAndView search(@RequestParam(value="q",required=false)String q,@RequestParam(value="page",required=false)String page,HttpServletRequest request) throws Exception{
		if(StringUtil.isEmpty(page)){page="1";}
		ModelAndView mav=new ModelAndView();
		mav.addObject("mainPage", "front/result.jsp");
		List<Blog> blogList = blogIndex.searchBlog(q.trim());
		Integer toIndex=blogList.size()>=Integer.parseInt(page)*10?Integer.parseInt(page)*10:blogList.size();
		mav.addObject("blogList",blogList.subList((Integer.parseInt(page)-1)*10, toIndex));
		mav.addObject("pageCode",this.genUpAndDownPageCode(Integer.parseInt(page), blogList.size(), q,10,request.getServletContext().getContextPath()));
		mav.addObject("q",q);
		mav.addObject("resultTotal",blogList.size());//查询结果总数
		mav.addObject("pageTitle","搜索关键字'"+q+"'结果页面_kinglone博客系统");
		mav.setViewName("mainTemp");
		return mav;
	}
	/**
	 * 获取上一页，下一页代码 查询博客用到
	 * @param page 当前页
	 * @param totalNum 总记录数
	 * @param q 查询关键字
	 * @param pageSize 每页大小
	 * @param projectContext
	 * @return
	 */
	private String genUpAndDownPageCode(Integer page,Integer totalNum,String q,Integer pageSize,String projectContext){
		long totalPage=totalNum%pageSize==0?totalNum/pageSize:totalNum/pageSize+1;
		StringBuffer pageCode=new StringBuffer();
		if(totalPage==0){
			return "";
		}else{
			pageCode.append("<nav>");
			pageCode.append("<ul class='pager' >");
			if(page>1){
				pageCode.append("<li><a href='"+projectContext+"/front/q.html?page="+(page-1)+"&q="+q+"'>上一页</a></li>");
			}else{
				pageCode.append("<li class='disabled'><a href='#'>上一页</a></li>");
			}
			if(page<totalPage){
				pageCode.append("<li><a href='"+projectContext+"/front/q.html?page="+(page+1)+"&q="+q+"'>下一页</a></li>");				
			}else{
				pageCode.append("<li class='disabled'><a href='#'>下一页</a></li>");				
			}
			pageCode.append("</ul>");
			pageCode.append("</nav>");
		}
		return pageCode.toString();
	}
}
